package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/11/20.
 */
public class SamePriceCarFragment extends BaseScrollFragment implements NetDataJson.OnNetDataJsonListener{

    protected boolean isVisible;

    private boolean isPrepared;

    private boolean isFirst = true;

    private NetDataJson mNetCarDetail;


    private ListView listView;

    private View view;

    private ImageView imageView;


    private CarBuyDetailActivity carBuyDetailActivity;
    /**
     * 同城好车的adapter
     */
    private CarSourceListAdapter mAdapter;

    /**
     * 同城好车数据
     */
    private List<CarSource> mCarBuyDetailsList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        action = "detail_samePriceCar";
        isScrollPage = true;
        view = inflater.inflate(R.layout.same_price_car_layout , container , false);
        isPrepared = true;
        lazyLoad();
        return view;
    }

    private void initView(){
        listView = (ListView) view.findViewById(R.id.list_view);
        imageView= (ImageView) view.findViewById(R.id.no_data);
        carBuyDetailActivity = (CarBuyDetailActivity) getActivity();
        mAdapter = new CarSourceListAdapter(carBuyDetailActivity);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PointRecordManage.getInstance().addPoint(getActivity(), Piont.SourceSamePriceDetailClick);
                Intent intent = new Intent();
                intent.setClass(getActivity(), CarBuyDetailActivity.class);
                CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
                intent.putExtra("typevalue", String.valueOf(carSource.mId));
                intent.putExtra("type", "sameprice");
                intent.putExtra("from", "sameprice");
                startActivity(intent);
            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();
        } else {
            isVisible = false;
        }
    }


    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }
        initView();
        getData();
        isFirst = false;
        //填充各控件的数据
    }

    private void getData(){
        carBuyDetailActivity.showProgressDialog();
        mNetCarDetail = new NetDataJson(this);
        mNetCarDetail.setUrl("/mobile/buy/get-same-price-cars/");
        mNetCarDetail.addParam("car_id", carBuyDetailActivity.mProductId);
        mNetCarDetail.request("get");
    }


    public void loadDataSuccess(JSONObject jsonProduct){
        JSONArray jsonArray = null;
        try {
            jsonArray = jsonProduct.getJSONArray("data");
            if (0 == jsonArray.length()) {
                imageView.setVisibility(View.VISIBLE);
                return;
            }
            mCarBuyDetailsList = new ArrayList<>(jsonArray.length());
            getDataFromJsonArray(jsonArray);
        } catch (JSONException e) {
            imageView.setVisibility(View.VISIBLE);
        }
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.mCity = object.getString("city");
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = "";
            carSrc.hasmodel =  object.getString("has_model_detail");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.mUrl = carSrc.mThumbnail;
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.dealer_category =  object.getString("dealer_category");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.brand_zh = "";
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            mCarBuyDetailsList.add(carSrc);
        }
        mAdapter.setData(mCarBuyDetailsList);

    }

    @Override
    public void onDataJsonError(String errorMessage) {
        isFirst = false;
        Toast.makeText(carBuyDetailActivity, errorMessage, Toast.LENGTH_SHORT).show();
        carBuyDetailActivity.hidenProgressDialog();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        loadDataSuccess(json);
        carBuyDetailActivity.hidenProgressDialog();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetCarDetail != null) {
            mNetCarDetail.cancelTask();
            mNetCarDetail = null;
        }
    }
}
